package com.ecplatform.user.controller;

import cn.hutool.core.bean.BeanUtil;
import com.ecplatform.common.constant.MessageConstants;
import com.ecplatform.common.exception.UserAlreadyExistsException;
import com.ecplatform.common.exception.UserException;
import com.ecplatform.common.pojo.po.Result;
import com.ecplatform.common.utils.PasswordEncryptionUtil;
import com.ecplatform.user.pojo.dto.UserDTO;
import com.ecplatform.user.pojo.po.User;
import com.ecplatform.user.pojo.vo.UserVO;
import com.ecplatform.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor    // Lombok注解，自动生成构造函数，用于注入依赖对象
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private final IUserService userService;


    /**
     * 用户注册
     * @param userDTO
     * @return
     * @throws UserAlreadyExistsException
     */
    @PostMapping("/register")
    public Result<UserVO> register(@RequestBody UserDTO userDTO) throws UserAlreadyExistsException{
        // 先转换DTO到PO
        User user = BeanUtil.copyProperties(userDTO, User.class);

        User newUser = userService.getByUsername(user.getUsername()); // 检查用户名是否存在

        // 判断是否用户已经存在，如果存在则抛出用户存在异常
        if (newUser != null) {
            throw new UserAlreadyExistsException(MessageConstants.UserIsExit);
        }

        // 保存用户信息到数据库
//        userServiceImpl.save(user);

        userService.insertUser(user);


        // 转换PO到VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        return Result.success(userVO);
    }

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO) throws UserException,Exception {
        UserVO userVO = userService.userLogin(userDTO);

        return Result.success(userVO);
    }
}